package com.gitee.ywj1352.template;

import com.gitee.ywj1352.template.model.RowMapper;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 模板模式
 */
public  class JdbcTemplate {

    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource){
        this.dataSource = dataSource;
    }


    private Connection getConnection() throws SQLException {
        return this.dataSource.getConnection();
    }

    private PreparedStatement createPreparedStatement(Connection conn,String sql) throws SQLException {
        return conn.prepareCall(sql);
    }

    private ResultSet executeQuery(PreparedStatement pstm,Object[] values) throws Exception{

        for (int i = 0;i<values.length;i++){
            pstm.setObject(i,values[i]);

        }
        return pstm.executeQuery();
    }

    private void closeStatement(Statement statement) throws SQLException {
        statement.close();
    }
    private List<?> parseResultSet(ResultSet rs,RowMapper rowMapper) throws Exception{

        List<Object> result = new ArrayList<Object>();
        int rowNum = 1;
        while(rs.next()){
            result.add(rowMapper.mapRow(rs,rowNum));
            rowNum ++;
        }

        return result;

    }


    public List<?> executeQuery(String sql, RowMapper<?> rowMapper, Object[]values){
        try {
            //1. 获取连接
            Connection conn = dataSource.getConnection();

            //2.创建语句集
            PreparedStatement pstm = conn.prepareStatement(sql);

            //3.执行语句集,并且获取结果集
            ResultSet rs = this.executeQuery(pstm,values);

            //4.解析语句集
            List<?> result = this.parseResultSet(rs, rowMapper);
            //5.关闭结果集
            rs.close();

            //6.关闭语句集
            this.closeStatement(pstm);

            //7.关闭连接
            conn.close();
            return result;



        }catch (Exception e){
            e.printStackTrace();
        }


        return null;
    }

   // public abstract Object processResult(ResultSet rs,int rowNum) throws SQLException;

}
